package com.af.timer;  
  
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.aote.logic.LogicServer;
import com.aote.sql.SqlServer;

// 从数据库中获取数据，发送给物联网表的主程序
@Transactional
public class UserBalance {
	private final Object lock = new Object();
	private static boolean isBusy = false;

	private static final Object JSONObject = null;

	private static Logger log = Logger.getLogger(UserBalance.class);

	@Autowired
	private SqlServer sqlServer;

	@Autowired
	private LogicServer logicServer;

	// 用户结余定时结算
	private String userBalance;

	

	public void main() {

		try {
			synchronized (lock) {
				if (isBusy) {
					log.debug("上次任务正在进行，请等待。。。。。。");
					return;
				} else {
					isBusy = true;
				}
			}
			// 所有过程如果出现异常，等下次再处理
			try {
				createArea();
				System.out.println("=============用户结余结算完成==================");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			synchronized (lock) {
				isBusy = false;
			}
		}

	}

	// 用户结余定时结算
	private void createArea() throws Exception {
	    Calendar cale = null;  
        cale = Calendar.getInstance(); 

        // 获取当月第一天和最后一天  
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
        String firstday, lastday;  
        // 获取前月的第一天  
        cale = Calendar.getInstance();  
        cale.add(Calendar.MONTH, 0);  
        cale.set(Calendar.DAY_OF_MONTH, 1);  
        firstday = format.format(cale.getTime())+" 00:00:00";  
        // 获取前月的最后一天  
        cale = Calendar.getInstance();  
        cale.add(Calendar.MONTH, 1);  
        cale.set(Calendar.DAY_OF_MONTH, 0);  
        lastday = format.format(cale.getTime())+" 23:59:59";  
        System.out.println("本月第一天和最后一天分别是 ： " + firstday + " and " + lastday);   
        JSONObject data = new JSONObject();
        data.put("startdate", firstday);
        data.put("enddate", lastday);
        System.out.println("data:"+data.toString());

		logicServer.run("userBalance", data);
	}

	

}